package com.zhangsun.springShiro.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangsun.springShiro.common.provider.RedisProvider;
import com.zhangsun.springShiro.system.entity.ResourceEntity;
import com.zhangsun.springShiro.system.entity.RoleEntity;
import com.zhangsun.springShiro.system.mapper.ResourceMapper;
import com.zhangsun.springShiro.system.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author zhangsun
 * @since 2019-07-23
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, ResourceEntity> implements ResourceService {

    @Autowired
    private RedisProvider redisProvider;

    @Override
    public List<ResourceEntity> findResourcesByRoles(List<RoleEntity> roles, String userId) {
        String resourcesObject = (String) redisProvider.get(userId + ":resource");
        if (StrUtil.isNotBlank(resourcesObject)) {
            return JSON.parseArray(resourcesObject, ResourceEntity.class);
        }

        Set<String> roleIds = new HashSet<>();
        if (CollUtil.isNotEmpty(roles)) {
            roles.forEach(r -> roleIds.add(r.getId()));
            List<ResourceEntity> resources = baseMapper.findResourcesByRoles(roleIds);
            redisProvider.set(userId + ":resource", JSON.toJSONString(resources));
            return resources;
        }
        return null;
    }
}
